<template>
  <div class="box" ref="boxRef">
    <div ref="printBox" class="code-image">
      <div id="qrCodeBox" ref="qrCodeBox"></div>
      <div id="hint" class="print-info">{{hint}}</div>
    </div>
    <div class="box-name">{{boxName}}</div>
    <el-row v-if="isEnable">
      <el-button :disabled="!isEnable" type="primary" :size="btnSize" @click="save">保存</el-button>
      <el-button :disabled="!isEnable" style="margin-left:20px" type="primary" :size="btnSize" @click="print">打印
      </el-button>
    </el-row>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2';
  export default {
    props: {
      qrWidth: {
        type: Number,
        default: 120
      },
      qrHeight: {
        type: Number,
        default: 120
      },
      btnSize: {
        type: String,
        default: 'mini'
      },
      boxName: {
        type: String,
        default: '',
        required: true
      },
      qrContent: {
        type: String,
        default: ''
      },
      qrStyle: {
        type: Object,
        default: function () {
          return {
            text: '',
            width: this.qrWidth,
            height: this.qrHeight,
            colorDark: "#16bc83", //二维码颜色
            colorLight: "#ffffff", //二维码背景色
            correctLevel: QRCode.CorrectLevel.L //容错率，L/M/H
          }
        }
      },
      hint: {
        type: String,
        default: ''
      },
      isPrintHint: {
        type: Boolean,
        default: false
      },
      printStyle: {
        type: String,
        default: ''
      }
    },
    watch: {
      qrContent(val) {
        this.qrStyle.text = val
        this.isEnable = (typeof val == "string") && val.length > 0
        this.bindQRCode()
      }
    },
    data() {
      return {
        isEnable: false,
        qrCode: null,
      }
    },
    methods: {
      bindQRCode: function () {
        try {
          if (this.qrStyle && this.qrStyle.text) {
            if (!this.qrStyle.correctLevel) {
              this.qrStyle.correctLevel = QRCode.CorrectLevel.L
            }
            if (!this.qrStyle.colorDark) {
              this.qrStyle.colorDark = "#16bc83"
            }
            if (!this.qrStyle.colorLight) {
              this.qrStyle.colorLight = "#ffffff"
            }
            if (!this.qrStyle.width) {
              this.qrStyle.width = this.qrWidth
            }
            if (!this.qrStyle.height) {
              this.qrStyle.height = this.qrHeight
            }
            if (this.qrCode) {
              this.qrCode.clear(); // 清除二维码
              this.qrCode.makeCode(this.qrStyle.text); // 生成另外一个二维码
            } else {
              this.qrCode = new QRCode(this.$refs.qrCodeBox, this.qrStyle);
            }
          } else {
            this.$message.error("二维码生成参数为空");
          }
        } catch (e) {
          console.log(e)
          this.$message.error(e)
        }
      },
      save() {
        try {
          //找到需要转换的canvas
          var data = this.$refs.qrCodeBox.children[0].toDataURL().replace("image/png",
            "image/octet-stream;"); //获取二维码值，并修改响应头部。
          var filename = `${this.hint||this.qrContent}.png`; //保存的图片名称和格式，canvas默认使用的png格式。这个格式效果最好。
          var save_link = document.createElement('a');
          save_link.href = data;
          save_link.download = filename;
          save_link.click()
        } catch (e) {
          console.log(e)
          this.$message.error(e)
        }
      },
      print() {
        try {
          var content = this.$refs.printBox.innerHTML;
          var iframe = document.createElement('iframe');
          var f = document.body.appendChild(iframe);
          iframe.id = "myIframe";
          iframe.setAttribute('style', "display:table;position:relative;width:0px;height:0px;top:-10px;left:-10px;");
          var w = f.contentWindow || f.contentDocument;
          var doc = f.contentDocument || f.contentWindow.document;
          doc.open();
          doc.write(content);
          var qrBox = doc.getElementById("qrCodeBox");
          var ptStyle = this.printStyle
          if (!ptStyle) {
            ptStyle =
              `display:table-cell;vertical-align:middle;position:absolute;top:50%;left:50%;margin-top:-${this.qrWidth/2};margin-left:-${this.qrHeight/2};`
          }
          qrBox.setAttribute('style', ptStyle)
          var div = doc.getElementById('hint')
          var isShowHint = this.isPrintHint && this.hint
          div.style.display = isShowHint ? 'inline' : 'none';
          doc.close();
          w.focus();
          w.print();
          document.body.removeChild(iframe)
          w.close();
        } catch (e) {
          console.log(e)
          this.$message.error(e)
        }
      },
    }
  }

</script>

<style lang="scss" scoped>
  .box {
    width: 100%;
    height: 100%;

    .code-image {
      display: inline-block;
    }

    .print-info {
      display: none;
      width: 100%;
      text-align: center;
      font-size: 16px;
      margin-top: 22px;
    }

    .box-name {
      font-size: 12px;
      margin-top: 8px;
      margin-bottom: 8px;
    }
  }

</style>
